import re

#TODO: Remove the ability to use a external pattern
class EpisodeRegex(object):
    
    #Episodes like [PUNCH]_Naruto_Shippuuden_-_190.mkv or [NS MX] Naruto Shippuuden - 130 HD.mkv
    __AUXILIAR_REGEX_PATTERN = "(naruto).*(shippuuden)[^\d]*?(\d+)(-\d+)?.*\.{1}(%s){1}$"
    
    #Exactelly Naruto Shippuuden.S01.E190.mkv
    _MAIN_REGEX_PATTERN = "(Naruto Shippuuden).S(\d+)E(\d+)(-\d+)?.(%s){1}$"
    
    __DEFAULT_ALLOWED_EXTENSIONS = ["mkv", "avi", "mp4"]
    
    def __init__(self, extensions=None):        
        mainPattern = self.__buildPattern(self._MAIN_REGEX_PATTERN, extensions)
        self.__mainRegex = re.compile(mainPattern, re.IGNORECASE)
        
        auxiliarPattern = self.__buildPattern(self.__AUXILIAR_REGEX_PATTERN, extensions)
        self.__auxiliarRegex = re.compile(auxiliarPattern, re.IGNORECASE)
        
        
    def __buildPattern(self, pattern, extensions):
        exts = self.__DEFAULT_ALLOWED_EXTENSIONS
        if extensions is not None:
            exts = extensions
            
        regexpPattern = pattern % ("|".join(exts))    
        return regexpPattern
    
    
    def search(self, obj):
        match = self.__mainRegex.search(obj)
        if match is None:
            match = self.__auxiliarRegex.search(obj)
        return match